package com.dzsw.javabase.file;

import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.List;

public class ModifyBinaryFile {

    private static final List<Long> NAME_ADDR_LIST = Arrays.asList(0x6DF1E0 + 4L, 0x6DF240 + 8L, 0x6DF300L, 0x6DF330 + 12L);

    public static void main(String[] args) throws Exception {
        if (args.length != 2) {
            throw new RuntimeException("parameters error! need two parameters: fileFullPath and newName.");
        }
        writeFile(args[0], args[1]);
    }

    private static void writeFile(String filePath, String newName) throws Exception{
        try (final RandomAccessFile raf = new RandomAccessFile(filePath, "rw")) {
            byte[] nameBytes = newName.getBytes(StandardCharsets.ISO_8859_1);
            for (Long addr : NAME_ADDR_LIST) {
                for (int i = 0; i < 17; i++) {
                    raf.seek(addr + i);
                    if (i % 2 == 0) {
                        int index = i / 2;
                        if (index > nameBytes.length - 1) {
                            raf.writeByte(randomChar());
                        } else {
                            raf.writeByte(nameBytes[index]);
                        }
                    }
                }
            }
        }
    }

    private static byte randomChar() {
        // 创建Random对象
        SecureRandom random = new SecureRandom();
        // 随机决定是大写还是小写字母 (0表示大写，1表示小写)
        boolean isUpperCase = random.nextBoolean();
        byte randomLetter;
        if (isUpperCase) {
            // 生成大写字母 (A-Z，ASCII码65-90)
            // 生成0-25之间的随机数，加上65得到对应的ASCII码
            randomLetter = (byte) (random.nextInt(26) + 'A');
        } else {
            // 生成小写字母 (a-z，ASCII码97-122)
            // 生成0-25之间的随机数，加上97得到对应的ASCII码
            randomLetter = (byte) (random.nextInt(26) + 'a');
        }
        return randomLetter;
    }
}
